import 'dart:convert';
import 'package:lib_util/SPUtils.dart';
import 'package:flutter/material.dart';
import 'ColorSourceInterface.dart';
import 'SourceManager.dart';

///播放列表管理
class PlayListManager {
  //sp素材保存的key
  static const String KEY_SOURCE_PARTITION = "play_list_key_source_partition_v1";

  //单例
  static PlayListManager instance = PlayListManager._();

  //播放列表id
  List<int> playListIds = [];

  PlayListManager._() {
    String json = SPUtils.getAsString(KEY_SOURCE_PARTITION);
    if (json.isNotEmpty) {
      // 从 JSON 转换回 List<int>
      List<dynamic> decodedList = jsonDecode(json);
      playListIds = List<int>.from(decodedList);
    }
  }

  void savePlayList(List<ColorSourceInterface> partition) {
    playListIds.clear();
    for (var i = 0; i < partition.length; i++) {
      playListIds.add(partition[i].id);
    }
    SPUtils.setAsString(KEY_SOURCE_PARTITION, jsonEncode(playListIds));
  }
  void savePlayListForId(List<int> partition) {
    playListIds.clear();
    playListIds.addAll(partition);
    SPUtils.setAsString(KEY_SOURCE_PARTITION, jsonEncode(playListIds));
  }

  List<ColorSourceInterface> getPlayList(Size screenSize) {
    List<ColorSourceInterface> data = [];
    for (int id in playListIds) {
      var bean = SourceManager.instance.getSourceForId(id);
      if (bean != null && bean.screenSize == screenSize) {
        data.add(bean);
      }
    }
    savePlayList(data);
    return data;
  }
}
